#include "QClientInit.h"
#include "../QCommon/QCommon.h"
#include <sys/msg.h>
#include <pthread.h>
#include <iostream>
using namespace std;
int QClientInit::register_client()
{
    int fd=open(Q_CS_FIFO,O_WRONLY);
    struct CSData d;
    d.pid=getpid();
    d.msqid=msgget(IPC_PRIVATE,IPC_CREAT|IPC_EXCL|0666);
    write(fd,&d,sizeof(CSData));
    close(fd);
    ACK ack;
    msgrcv(d.msqid,&ack,sizeof(char),0,0);
    QClientMsqId=d.msqid;
    return d.msqid;
}

void QClientInit::generate_map()
{
    eh_map[msg]=new MsgHandler();
    eh_map[network]=new NetworkHandler();
    eh_map[file_answer]=new FileAnswerHandler();
    eh_map[file_ask]=new FileAskHandler();
}

void* event_handle(void *arg)
{
    QClientInit *init=(QClientInit*)arg;
    char *event=new char[MAX_EVENT_SIZE];
    while(true)
    {
        msgrcv(QClientMsqId,event,MAX_EVENT_SIZE,0,0);
        AbstractEvent *e=(AbstractEvent*)event;
        AbstractHandler *handler=init->eh_map[e->type];
        if(handler!=NULL)
        {
            handler->handle(*e);
        }
    }
    return NULL;
}

void QClientInit::start_handle()
{
    pthread_t tid;
    pthread_create(&tid,NULL,event_handle,this);
}

int QClientMsqId;
